package com.sfx.admin.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sfx.admin.common.constants.RedisCacheConstants;
import com.sfx.admin.common.convention.exception.ClientException;
import com.sfx.admin.common.enums.UserErrorCodeEnums;
import com.sfx.admin.common.utils.BeanUtils;
import com.sfx.admin.dao.entity.UserDO;
import com.sfx.admin.dao.mapper.IUserMapper;
import com.sfx.admin.dto.req.UserLoginReqDTO;
import com.sfx.admin.dto.req.UserRegisterReqDTO;
import com.sfx.admin.dto.req.UserUpdateReqDTO;
import com.sfx.admin.dto.resp.UserLoginRespDTO;
import com.sfx.admin.dto.resp.UserRespDTO;
import com.sfx.admin.service.IGroupService;
import com.sfx.admin.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.sfx.admin.common.constants.RedisCacheConstants.SHORT_LINK_USER_LOGIN_CACHE_KEY;
import static com.sfx.admin.common.enums.UserErrorCodeEnums.*;


@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<IUserMapper, UserDO>
        implements IUserService {

    /**
     * 引入布隆过滤器 ,用于存放用户名,保证用户名的唯一性, 防止用户名重复注册
     */
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final StringRedisTemplate stringRedisTemplate;
    private final RedissonClient redissonClient;
    private final IGroupService groupService;

    @Override
    public UserRespDTO getUserByUserName(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException(USER_NOT_EXISTS);
        }
        return BeanUtils.convert(userDO, UserRespDTO.class);
    }

    /**
     * 检查用户名是否存在
     *
     * @param username 用户名
     * @return 用户存在返回false, 用户不存在 返回true
     */
    @Override
    public Boolean hasUsername(String username) {
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    /**
     * 用户注册
     *
     * @param requestParam UserRegisterReqDTO
     */
    @Override
    public void register(UserRegisterReqDTO requestParam) {
        String username = requestParam.getUsername();
        // 1. 检查用户名是否存在,如果用户名存在,则不能注册
        if (!hasUsername(username)) {
            // 用户名已经存在
            throw new ClientException(UserErrorCodeEnums.USER_NAME_ALREADY_EXISTS);
        }
        // 这里还需要防止大量用户重复注册
        // 这里只能防止短时间内相同用户名的重复注册
        RLock lock = redissonClient
                .getLock(RedisCacheConstants.SHORT_LINK_USER_REGISTER_CACHE_KEY + username);
        try {
            if (lock.tryLock()) {
                // 2. 如果用户名不存在,则进行注册
                try {
                    int insert = baseMapper.insert(BeanUtils.convert(requestParam, UserDO.class));
                    if (insert < 1) {
                        throw new ClientException(UserErrorCodeEnums.USER_SAVE_FAIL);
                    }
                } catch (DuplicateKeyException ex) {
                    throw new ClientException(USER_ALREADY_EXISTS);
                }
                // 3. 如果保存用户名成功,就保存到布隆过滤器中
                userRegisterCachePenetrationBloomFilter.add(username);
                // 4. 用户注册完成后,必须要有一个分组--> 默认分组
                groupService.saveGroup(username,"默认分组");
                return;
            }
            throw new ClientException(UserErrorCodeEnums.USER_NAME_ALREADY_EXISTS);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 用户个人信息修改
     *
     * @param requestParam UserUpdateReqDTO
     */
    @Override
    public void update(UserUpdateReqDTO requestParam) {
        LambdaQueryWrapper<UserDO> queryWrapper =
                Wrappers.lambdaQuery(UserDO.class)
                        .eq(UserDO::getUsername, requestParam.getUsername());
        int update = baseMapper.update(BeanUtils.convert(requestParam, UserDO.class), queryWrapper);
        if (update < 1) {
            throw new ClientException(USER_UPDATE_FAIL);
        }
    }

    /**
     * 用户登陆功能
     *
     * @param requestParam UserLoginReqDTO
     * @return
     */
    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        // 1. 验证用户名和密码
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword());
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException(USER_NOT_EXISTS);
        }
        // 2. 生成token
        String token = UUID.randomUUID().toString();
        String loginKey = SHORT_LINK_USER_LOGIN_CACHE_KEY + requestParam.getUsername();
        if (stringRedisTemplate.opsForHash().get(loginKey, token) != null) {
            // 用户已经登陆了
            throw new ClientException(USER_ALREADY_LOGIN);
        }
        // 3. token有效期30分钟有效
        // key1 :  userName     key2 : token    value : 用户信息
        stringRedisTemplate.opsForHash().put(loginKey, token, JSON.toJSONString(userDO));
        stringRedisTemplate.expire(loginKey, 30, TimeUnit.DAYS);
        return new UserLoginRespDTO(token);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        String loginKey = SHORT_LINK_USER_LOGIN_CACHE_KEY + username;
        return stringRedisTemplate.opsForHash().get(loginKey, token) != null;
    }

    @Override
    public void logout(String username, String token) {
        String loginKey = SHORT_LINK_USER_LOGIN_CACHE_KEY + username;
        // 检查该用户有没有登陆,如果有,把它删除了
        if (checkLogin(username, token)) {
            stringRedisTemplate.opsForHash().delete(loginKey, token);
            return;
        }
        throw new ClientException(USER_NOT_LOGIN);
    }
}